package kr.or.kosta.otr.controller.reviewcontroller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.StringTokenizer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import kr.or.kosta.otr.service.reviewservice.ReviewService;
import kr.or.kosta.otr.vo.AdminVO;
import kr.or.kosta.otr.vo.CompanyReviewTypeVO;
import kr.or.kosta.otr.vo.CompanyReviewVO;
import kr.or.kosta.otr.vo.CompanyReviewVerifyVO;
import kr.or.kosta.otr.vo.CompanyVO;
import kr.or.kosta.otr.vo.IndustryVO;
import kr.or.kosta.otr.vo.InterestCompanyVO;
import kr.or.kosta.otr.vo.MentorVO;
import kr.or.kosta.otr.vo.MessageTypeVO;
import kr.or.kosta.otr.vo.MessageVO;
import kr.or.kosta.otr.vo.ProfessionVO;
import kr.or.kosta.otr.vo.RegionVO;
import kr.or.kosta.otr.vo.ScoreVO;
import kr.or.kosta.otr.vo.TrueOrFalseVO;
import kr.or.kosta.otr.vo.UserVO;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ReviewController {

	@Resource(name = "ReviewService")
	ReviewService reviewService;

	@RequestMapping(value = "/getAllList.action")
	public ModelAndView getAllList(@ModelAttribute UserVO vo)
			throws SQLException {
		HashMap<String, ArrayList> map = new HashMap<String, ArrayList>();

		ArrayList<CompanyVO> companyList = reviewService.getAllCompany();
		ArrayList<IndustryVO> industryList = reviewService.getAllIndustry();
		ArrayList<RegionVO> regionList = reviewService.getAllRegion();
		ArrayList<ProfessionVO> professionList = reviewService.getAllProfession();
		map.put("companyList", companyList);
		map.put("industryList", industryList);
		map.put("regionList", regionList);
		map.put("professionList", professionList);
		return new ModelAndView("company_review/company_review_main_write",
				"listMap", map);
	}

	@RequestMapping(value = "/writeCompanyReview.action")
	public ModelAndView writeCompanyReview(
			@ModelAttribute CompanyReviewVO crvo,
			@ModelAttribute ScoreVO svo,
			@RequestParam(value = "companyName") String companyName,
			@RequestParam(value = "professionName") String professionName,
			@RequestParam(value = "companyReviewSalary") int companyReviewSalary,
			@RequestParam(value = "companyReview") String companyReview,
			@RequestParam(value = "companyMerit") String companyMerit,
			@RequestParam(value = "companyDemerit") String companyDemerit,
			HttpServletRequest request) throws SQLException {

		HashMap<String, Object> map = new HashMap<String, Object>();

		// score입력 및 바인딩
		reviewService.writeScore(svo);
		crvo.setScoreVo(svo);
		reviewService.updateTotalScore(svo.getScoreId());

		// companyId 바인딩
		map.put("company", "company_name");
		map.put("companyValue", companyName);
		ArrayList<CompanyVO> clist = reviewService.getCompanyInfo(map);
		crvo.setCompanyVo(clist.get(0));

		// professionId 방인딩
		map.put("profession", "profession_name");
		map.put("professionValue", professionName);
		ProfessionVO pvo = reviewService.getProfession(map);
		crvo.setProfessionVo(pvo);

		// 나머지것들 바인딩
		crvo.setCompanyReviewSalary(companyReviewSalary);

		HttpSession session = request.getSession();
		UserVO userVo = (UserVO) session.getAttribute("userVo");
		AdminVO adminVo = (AdminVO) session.getAttribute("adminVo");
		if (userVo != null) {
			crvo.setCompanyReviewUserId(userVo.getUserId());
		} else if (adminVo != null) {
			crvo.setCompanyReviewUserId(adminVo.getAdminId());
		}

		// 글입력
		reviewService.writeCompanyReview(crvo);
		CompanyReviewVerifyVO crvvo1 = new CompanyReviewVerifyVO(0, crvo,
				new CompanyReviewTypeVO(1, "기업리뷰"), companyReview);
		CompanyReviewVerifyVO crvvo2 = new CompanyReviewVerifyVO(0, crvo,
				new CompanyReviewTypeVO(2, "장점"), companyMerit);
		CompanyReviewVerifyVO crvvo3 = new CompanyReviewVerifyVO(0, crvo,
				new CompanyReviewTypeVO(3, "단점"), companyDemerit);

		// 내용 입력
		int i = reviewService.writeCompanyReviewVerify(crvvo1);
		int x = reviewService.writeCompanyReviewVerify(crvvo2);
		int y = reviewService.writeCompanyReviewVerify(crvvo3);
		// 진실 거짓 생성
		reviewService.insertTruthOrFalse(i);
		reviewService.insertTruthOrFalse(x);
		reviewService.insertTruthOrFalse(y);

		// 포인트 증가
		if (userVo != null) {
			map.put("point", 30);
			map.put("userId", userVo.getUserId());
			reviewService.updatePointPlus(map);
			int point = reviewService.getUserPoint(userVo.getUserId());
			userVo.setUserPoint(point);
		}
		
		//관심기업에 등록된 사람들한테 알림보내기
		map.put("messageType", "message_type_id");
		map.put("messageTypeValue", 2);
		MessageTypeVO mtvo = reviewService.getMessageType(map);
		ArrayList<InterestCompanyVO> icList = reviewService.getAllInterestCompanyList(clist.get(0).getCompanyId());
		for(int j=0; j<icList.size() ; j++){
			MessageVO mvo = new MessageVO(0, 
					mtvo, 
					icList.get(j).getUserVo().getUserId(), 
					userVo.getAdminVo().getAdminId(), 
					"관심 기업("+ clist.get(0).getCompanyName() +")에 리뷰가 추가되었습니다!");
			reviewService.writeMessage(mvo);
			
		}

		float total = reviewService.getCompanyScoreTotal(clist.get(0).getCompanyId());
		HashMap<String, Object> map1 = new HashMap<String, Object>();
		map1.put("companyTotalScore", Math.round(total * 100)/100.0 );
		map1.put("companyId", clist.get(0).getCompanyId());
		reviewService.setCompanyTotalScore(map1);
		
		return new ModelAndView("redirect:/getAllList.action");
	}

	@RequestMapping(value = "/getCompanyReview.action")
	public ModelAndView getCompanyReview(
			@RequestParam(value = "companyId") int companyId,
			@RequestParam(value="pageNo") String pageNo,
			HttpServletRequest request) throws SQLException {

		ModelAndView mav = new ModelAndView();
		CompanyVO company = reviewService.getOneCompany(companyId);

		mav.addObject("company", company);
		System.out.println("getCompanyReview 컴온");
		int isExist = reviewService
				.isExistCompanyReviewVerifyByCompanyId(companyId);
		// 리뷰 존재 여부
		if (isExist != 0) {
			// 기업의 스코어 찾기 및 바인딩
			float scoreChance = reviewService.getTotalScoreOfChance(company
					.getCompanyId());
			float scoreWelfare = reviewService.getTotalScoreOfWelfare(company
					.getCompanyId());
			float scoreCulture = reviewService.getTotalScoreOfCulture(company
					.getCompanyId());
			float scoreHoliday = reviewService.getTotalScoreOfHoliday(company
					.getCompanyId());
			float scoreExecutive = reviewService
					.getTotalScoreOfExecutive(company.getCompanyId());
			float scoreOverdue = reviewService.getTotalScoreOfOverdue(company
					.getCompanyId());
			HashMap<String, Object> modelMap = new HashMap<String, Object>();
			modelMap.put("scoreChance", Math.round(scoreChance * 100)/100.0);
			modelMap.put("scoreWelfare",  Math.round(scoreWelfare* 100)/100.0);
			modelMap.put("scoreCulture",  Math.round(scoreCulture* 100)/100.0);
			modelMap.put("scoreHoliday",  Math.round(scoreHoliday* 100)/100.0);
			modelMap.put("scoreExecutive",  Math.round(scoreExecutive* 100)/100.0);
			modelMap.put("scoreOverdue",  Math.round(scoreOverdue* 100)/100.0);
			mav.addAllObjects(modelMap);

			// total 정보 바인딩
			float total = reviewService.getCompanyScoreTotal(companyId);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("companyTotalScore", Math.round(total * 100)/100.0 );
			map.put("companyId", companyId);
			reviewService.setCompanyTotalScore(map);
			mav.addObject("total", Math.round(total * 100)/100.0);
			// 멘토 정보 가져오기
			HashMap<String, Object> map1 = new HashMap<String, Object>();
			map1.put("company", "company_id");
			map1.put("companyValue", companyId);
			ArrayList<MentorVO> mv = reviewService.getAllMentor(map1);
			mav.addObject("mv", mv);
	
			//Total
			double Total = reviewService.getCompanyReviewVerifyByCompanyIdTotal(companyId);
			
			mav.addObject("page", Math.ceil(Total/9));
			mav.addObject("nowPage", pageNo);
			
			HashMap<String, Object> hmap = new HashMap<String, Object>();
			hmap.put("companyId", companyId);
			hmap.put("value", pageNo);
			System.out.println("hmap :: " + hmap);
			
			// reviewVerify 가져오기
			//ArrayList<TrueOrFalseVO> crv = reviewService.getCompanyReviewVerifyByCompanyId(companyId);
			ArrayList<TrueOrFalseVO> crv = reviewService.getCompanyReviewVerifyByCompanyIdPage(hmap);

			LinkedHashMap<String, ArrayList<TrueOrFalseVO>> linkmap = new LinkedHashMap<String, ArrayList<TrueOrFalseVO>>();
			int count = 1;
			for (int i = 0; i < crv.size();) {
				String userId = count
						+ " "
						+ crv.get(i).getCompanyReviewVerifyVO()
						.getCompanyReviewVO().getCompanyReviewUserId();
				ArrayList<TrueOrFalseVO> acrv = new ArrayList<TrueOrFalseVO>();
				// 리뷰 진실 거짓 값 넣어주기
				String s = crv.get(i).getTruth();
				int t = 0;
				StringTokenizer tk1 = new StringTokenizer(s, ",");
				while (tk1.hasMoreTokens()) {
					t++;
					tk1.nextToken();
				}
				crv.get(i).setT(t);
				String ob = crv.get(i).getObjection();
				int o = 0;
				StringTokenizer tk2 = new StringTokenizer(ob, ",");
				while (tk2.hasMoreTokens()) {
					o++;
					tk2.nextToken();
				}
				crv.get(i).setO(o);
				acrv.add(crv.get(i++));

				// 장점 진실 거짓 값 넣어주기
				String js = crv.get(i).getTruth();
				int jt = 0;
				StringTokenizer jtk1 = new StringTokenizer(js, ",");
				while (jtk1.hasMoreTokens()) {
					jt++;
					jtk1.nextToken();
				}
				crv.get(i).setT(jt);
				String job = crv.get(i).getObjection();
				int jo = 0;
				StringTokenizer jtk2 = new StringTokenizer(job, ",");
				while (jtk2.hasMoreTokens()) {
					jo++;
					jtk2.nextToken();
				}
				crv.get(i).setO(jo);
				acrv.add(crv.get(i++));
				// 거짓 진실 거짓 값 넣어주기
				String ks = crv.get(i).getTruth();
				int kt = 0;
				StringTokenizer ktk1 = new StringTokenizer(ks, ",");
				while (ktk1.hasMoreTokens()) {
					kt++;
					ktk1.nextToken();
				}
				crv.get(i).setT(kt);

				String kob = crv.get(i).getObjection();
				int ko = 0;
				StringTokenizer ktk2 = new StringTokenizer(kob, ",");
				while (ktk2.hasMoreTokens()) {
					ko++;
					ktk2.nextToken();
				}
				crv.get(i).setO(ko);

				acrv.add(crv.get(i++));

				linkmap.put(userId, acrv);
				count++;
			}
			mav.addObject("crv", linkmap);
		}
		// 존재 하지 않을 경우
		else {
			HashMap<String, Object> modelMap = new HashMap<String, Object>();
			modelMap.put("scoreChance", 0);
			modelMap.put("scoreWelfare", 0);
			modelMap.put("scoreCulture", 0);
			modelMap.put("scoreHoliday", 0);
			modelMap.put("scoreExecutive", 0);
			modelMap.put("scoreOverdue", 0);
			modelMap.put("total", 0);
			modelMap.put("crv", null);
			mav.addAllObjects(modelMap);
		}
		mav.setViewName("company_review/company_review_info");
		return mav;
	}

	@RequestMapping(value = "/increaseTruth.action")
	public ModelAndView increaseTruth(
			@RequestParam(value = "companyRevicewVerifyId") int companyRevicewVerifyId,
			HttpSession session) throws SQLException {

		boolean flag = false;
		String id = null;
		UserVO userVO = (UserVO) session.getAttribute("userVo");
		AdminVO adminVO = (AdminVO) session.getAttribute("adminVo");
		String s = reviewService
				.getOneTruthByReviewVerifyId(companyRevicewVerifyId);
		String s1 = reviewService
				.getOneObjectionByReviewVerifyId(companyRevicewVerifyId);
		if (userVO != null) {
			id = userVO.getUserId();
		}
		if (adminVO != null) {
			id = adminVO.getAdminId();
		}
		if (s != null) {
			StringTokenizer tk1 = new StringTokenizer(s, ",");
			while (tk1.hasMoreTokens()) {
				if (tk1.nextToken().equals(id)) {
					flag = true;
					break;
				}
			}
		}
		if (s1 != null) {
			StringTokenizer tk2 = new StringTokenizer(s1, ",");
			while (flag != true && tk2.hasMoreTokens()) {
				if (tk2.nextToken().equals(id)) {
					flag = true;
					break;
				}
			}
		}
		if (flag == true)
			return new ModelAndView("JsonView", "flag", flag);
		else {
			int truth = 0;
			HashMap<String, Object> map = new HashMap<String, Object>();
			String str;
			if (s != null) {
				str = s + "," + id;
			} else
				str = id;
			map.put("truth", str);
			map.put("companyReviewVerifyId", companyRevicewVerifyId);
			reviewService.increaseTruth(map);
			String f = reviewService
					.getOneTruthByReviewVerifyId(companyRevicewVerifyId);
			if (f != null) {
				StringTokenizer ftk = new StringTokenizer(f, ",");
				while (ftk.hasMoreTokens()) {
					truth++;
					ftk.nextToken();
				}
			}
			return new ModelAndView("JsonView", "truth", truth);
		}
	}

	@RequestMapping(value = "/increaseObjection.action")
	public ModelAndView increaseObjection(
			@RequestParam(value = "companyRevicewVerifyId") int companyRevicewVerifyId,
			HttpSession session) throws SQLException {
		boolean flag = false;
		String id = null;
		UserVO userVO = (UserVO) session.getAttribute("userVo");
		AdminVO adminVO = (AdminVO) session.getAttribute("adminVo");
		String s = reviewService
				.getOneTruthByReviewVerifyId(companyRevicewVerifyId);
		String s1 = reviewService
				.getOneObjectionByReviewVerifyId(companyRevicewVerifyId);
		if (userVO != null) {
			id = userVO.getUserId();
		}
		if (adminVO != null) {
			id = adminVO.getAdminId();
		}
		if (s != null) {
			StringTokenizer tk1 = new StringTokenizer(s, ",");
			while (tk1.hasMoreTokens()) {
				if (tk1.nextToken().equals(id)) {
					flag = true;
					break;
				}
			}
		}
		if (s1 != null) {
			StringTokenizer tk2 = new StringTokenizer(s1, ",");
			while (flag != true && tk2.hasMoreTokens()) {
				if (tk2.nextToken().equals(id)) {
					flag = true;
					break;
				}
			}
		}
		if (flag == true)
			return new ModelAndView("JsonView", "flag", flag);
		else {
			int objection = 0;
			HashMap<String, Object> map = new HashMap<String, Object>();
			String str;
			if (s1 != null) {
				str = s1 + "," + id;
			} else
				str = id;
			map.put("objection", str);
			map.put("companyReviewVerifyId", companyRevicewVerifyId);
			reviewService.increaseObjection(map);
			String f = reviewService
					.getOneObjectionByReviewVerifyId(companyRevicewVerifyId);
			if (f != null) {
				StringTokenizer ftk = new StringTokenizer(f, ",");
				while (ftk.hasMoreTokens()) {
					objection++;
					ftk.nextToken();
				}
			}
			return new ModelAndView("JsonView", "objection", objection);
		}
	}

	@RequestMapping(value = "/getCompanyInfoByCompanyName.action")
	public ModelAndView getCompanyInfoByCompanyName(
			@RequestParam(value = "companyName") String companyName)
					throws SQLException {

		// companyId
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("company", "company_name");
		map.put("companyValue", companyName);
		ArrayList<CompanyVO> clist = reviewService.getCompanyInfo(map);

		return new ModelAndView("JsonView", "clist", clist);
	}
}
